Date.prototype.Format = function (fmt) { //author: meizz
    var o = {
        "M+": this.getMonth() + 1, //月份
        "d+": this.getDate(), //日
        "h+": this.getHours(), //小时
        "m+": this.getMinutes(), //分
        "s+": this.getSeconds(), //秒
        "q+": Math.floor((this.getMonth() + 3) / 3), //季度
        "S": this.getMilliseconds() //毫秒
    };
    if (/(y+)/.test(fmt)) fmt = fmt.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length));
    for (var k in o)
        if (new RegExp("(" + k + ")").test(fmt)) fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));
    return fmt;
}

// Initialize your app
var myApp = new Framework7({
    precompileTemplates: true, //
    swipeBackPage:false,
    template7Pages: true
});

// Export selectors engine
var $$ = Dom7;

// Add view
var mainView = myApp.addView('.view-main', {
    // Because we use fixed-through navbar we can enable dynamic navbar
    //dynamicNavbar: true,
    domCache: true
});
var mfCusName,mfCusId;
myApp.showLoadingWithCallback=function(title,callbackFnc){
    var _modalTemplateTempDiv = document.createElement('div');
    var mdhtml = '<div class="modal modal-preloader"><div class="modal-inner"><div class="modal-title">'+title+'</div><div class="modal-text"><div class="preloader"></div></div></div></div>';
    _modalTemplateTempDiv.innerHTML = mdhtml;
    var modal = $(_modalTemplateTempDiv).children();
    $('body').append(modal[0]);
    //Preloader opened，可以处理图片了
    $$(modal).on("opened",function(){
        callbackFnc();
    });
    myApp.openModal(modal);
}

function checkLoginFields(){
    var phoneNumber = $$("#phoneNo").val();
    var pswd = $$("#password").val();
    //if(phoneNumber.length==11 && phoneNumber.match(/^1[3|4|5|8][0-9]\d{4,8}$/)!=null && pswd.match(/^[a-zA-Z0-9]{6,12}$/)!=null){
    if(phoneNumber.length==11&&pswd.match(/^[a-zA-Z0-9]{6,12}$/)!=null){
        return true;
    }else{
        return false;
    }
}
$$('.myLoginFields').on('keyup parste change', function () {
    if(checkLoginFields()){
        $$("#loginBtn").removeClass("disabled");
    }else{
        $$("#loginBtn").addClass("disabled");
    }
});

$$('.myLoginFields_Af').on('keyup parste change', function () {
    if(checkLoginFields()){
        $$("#loginBtn").removeClass("disabled");
    }else{
        $$("#loginBtn").addClass("disabled");
    }
});

$$("#loginBtn").click(function(){
    $$("#loginBtn").addClass("disabled");
    var terminalTypeId = $$("#terminalTypeId").val();
    if(checkLoginFields()){
        $$.ajax({
            type:'POST',
            url:  '../user/customerLogin.action',
            data:{
                phoneNo:$$("#phoneNo").val(),
                password:$$("#password").val(),
                terminalTypeId:terminalTypeId,
            },
            success: function(data){
            	saveStorage();
                var res = eval('('+data+')');
                if(res.code == '0'){
                    document.title = res.cusName;
                    mfCusName = res.cusName;
                    mfCusId = res.cusId;
                    var myCusStatus = res.cusStatus;
                    var statusShow = "";
                    if('TRUE' == myCusStatus){
                        statusShow = '<font color="green">正常</font>';
                    }else if('AUDITING' == myCusStatus){
                        statusShow = '<font color="red">审核中</font>';
                    }else if('FALSE' == myCusStatus){
                        statusShow = '<font color="red">审核失败</font>';
                    }
                    $$("#bi_cusNo").html(res.cusNo);
                    $$("#bi_cusStatus").html(statusShow);
                    $$("#bi_lastLoginTime").html(res.lastLoginTime);
                    $$("#bi_settleAccNo").html(res.settleAccNo);
                    $$("#bi_userMoney").html(res.userMoney);
                    if(mfCusId){
                        if(res.cusStatus==='FALSE'){
                            myApp.alert(res.msg,'',function () {
                                window.location.href = '../user/userAction_customerRegisterFetchInfo.action?activationCode='+res.cusId+"&terminalTypeId="+terminalTypeId;
                            });
                        }
                    }
                   mainView.router.load({pageName:'pageBaseInfo'});
                }else{
                    myApp.alert(res.msg);
                }
            },
            error:function(){
                myApp.alert( '登录失败');
                $$("#loginBtn").removeClass("disabled");
            }
        });
    }
});

function translateTransType(tt){
    if(tt==='3'){
        return '微信支付';
    }else if(tt === '4'){
        return '支付宝支付';
    }else{
        return tt;
    }
}
function translateTransStatus(ts,cs){
    if(cs === undefined || cs === 'undefined' || cs === null || cs === 'null' || cs === ''){
        if(ts === 0){
            return '失败';
        }else if(ts === 1){
            return '成功';
        }else if(ts === 2){
            return '处理中';
        }else if(ts === 3){
            return '未付';
        }else {
            return '未付';
        }
    }else if(cs === 0){
        return '提现失败';
    }else if(cs === 1){
        return '已提现';
    }else if(cs === 2){
        return '提现中';
    }else {
        return '提现中';
    }
}

function translateTransColor(ts){
    if(ts=== 1){
        return 'green';
    }else if(ts === 2){
        return 'blue';
    }else {
        return 'red';
    }
}
function getTransDetail(externalId){
    myApp.showLoadingWithCallback('正在查询...',function(){
        $$.ajax({
            type:'POST',
            url:  '../trans/transActionNL_customerTransactionDetail.action',
            data:{
                externalId:externalId
            },
            success: function(data){
                var res = eval('('+data+')');
                if(res.code == '9990' || res.code == '9991'){
                    myApp.hidePreloader();
                    myApp.alert(res.msg);
                    $$("#password").val('');
                    mainView.router.load({pageName:'pageLogin'});
                }
                if(res.code == '0'){
                    myApp.hidePreloader();
                    document.title = '交易详情';
                    mainView.router.load({
                        template: Template7.templates.pageTransDetailInfoTemplate, // template already compiled and available as a property of Template7.templates
                        context: res
                    });
                    if(res.cashBtn == '0'){//不显示按钮
                        document.getElementById("cashMoneyBtn").style.display = 'none';
                    }else if(res.cashBtn == '1'){//显示按钮
                        $$("#cashMoneyBtn").removeClass("hidden");
                        $$("#orderNum").val(res.orderNum);
                    }else if(res.cashBtn == '2'){//隐藏式按钮
                        $$("#cashMoneyBtn").removeClass("hidden");
                        $$("#cashMoneyBtn").addClass('disabled');
                    }

                }else{
                    myApp.hidePreloader();
                    myApp.alert( res.msg,function(){
                        if(res.code === '-2'){
                            location.replace(location.href);
                        }
                    });
                }
            },
            error:function(){
                myApp.hidePreloader();
                myApp.alert( '查询出错啦');
            }
        });
    });
}
//交易查询
var transListPageNo = 1;
var transListTotalPage=0;
function queryTransList(){
    $$.ajax({
        type:'POST',
        url:  '../trans/transActionNL_weChartTransactionList.action',
        data:{
            pageNo:transListPageNo,
            TotalPage:transListTotalPage
        },
        success: function(data){
            var res = eval('('+data+')');
            if(res.code == '9990' || res.code == '9991'){
                myApp.hidePreloader();
                myApp.alert(res.msg);
                $$("#password").val('');
                mainView.router.load({pageName:'pageLogin'});
            }
            if(res.code == '0000'){
                if(res.transList.length<1){
                    myApp.hidePreloader();
                    myApp.alert(res.msg);
                }else{
                    transListTotalPage = res.totalPage;
                    var html = '';
                    console.dir(res.transList);
                    for(var i=0;i<res.transList.length;i++){
                        var transType = translateTransType(res.transList[i].TRANS_TYPE);
                        var transStatus = translateTransStatus(res.transList[i].TRANS_STATE,res.transList[i].cashStatus);
                        var color = translateTransColor(res.transList[i].TRANS_STATE);
                        var orderNum = res.transList[i].orderNum;
                        html += ('<li>'+
                        '<a href="javascript:void(0);" class="item-link list-button" style="line-height:normal;" onclick="getTransDetail(\''+orderNum+'\')">'+
                        '<div class="item-inner">'+
                        '<table width="100%" style="color:#000000;border-collapse:separate; border-spacing:1px;">'+
                        '<tr><th style="text-align:left;">'+transType+'</th><th style="text-align:right;">'+res.transList[i].transMoney+'元</th><th rowspan="2" style="text-align:right;width:60px;color:'+color+'">'+transStatus+'</th></tr>'+
                        '<tr><td style="text-align:left;">'+new Date(res.transList[i].transTime.time).Format("yyyy-MM-dd hh:mm:ss")+'</td><td style="text-align:right;">'+res.transList[i].remark+'</td></tr>'+
                        '</table>'+
                        '</div>'+
                        '</a>'+
                        '</li>');
                    }
                    $$('.mf-trans-list ul').append(html);
                    myApp.hidePreloader();
                    $$("#pageTranListTitle").html(mfCusName);
                    document.title='交易查询';
                    mainView.router.load({pageName:'pageTranList'});
                }
            }else{
                myApp.hidePreloader();
                myApp.alert(res.msg,function(){
                    if(res.code === '-2'){
                        location.replace(location.href);
                    }
                });
            }
        },
        error:function(){
            myApp.hidePreloader();
            myApp.alert( '查询出错啦');
        }
    });
}
function tqBtnClick(){
    transListPageNo = 1;
    transListTotalPage=0;
    myApp.showLoadingWithCallback('正在查询...',function(){
        $$('.mf-trans-list ul').html('');
        queryTransList();
    });
}

function lazyLoadList() {
    var viewH =$$('#transListDiv').height(),//可见高度
        contentH = document.getElementById('transListDiv').scrollHeight,//内容高度
        scrollTop =$$('#transListDiv').scrollTop();//滚动高度
    if(scrollTop/(contentH -viewH)>=0.95){ //到达底部100px时,加载新内容
        ++transListPageNo;
        queryTransList();
    }
}

function translateSettleBillStatus(sbs){
    if(sbs==='SUCCESS'){
        return '付款成功';
    }else if(sbs === 'WAIT'){
        return '待付款';
    }else if(sbs === 'UNDERWAY'){
        return '付款中';
    }else if(sbs === 'FAIL'){
        return '付款失败';
    }else if(sbs === 'SUSPEND'){
        return '挂起，暂停';
    }else{
        return ts;
    }
}
//结算查询
var settleBillList;
function sqBtnClick(){
    myApp.showLoadingWithCallback('正在查询...',function(){
        $$('.mf-settle-bill-list ul').html('');
        $$.ajax({
            type:'POST',
            url:  '../trans/transActionNL_weChartSettleList.action',
            success: function(data){
                var res = eval('('+data+')');
                if(res.code == '0000'){
                    if(res.code == '9990' || res.code == '9991'){
                        myApp.hidePreloader();
                        myApp.alert(res.msg);
                        $$("#password").val('');
                        mainView.router.load({pageName:'pageLogin'});
                    }
                    if(res.settleBillList.length<1){
                        myApp.hidePreloader();
                        myApp.alert(res.msg);
                    }else{
                        var html = '';
                        settleBillList = res.settleBillList;
                        for(var i=0;i<res.settleBillList.length;i++){
                            var settleBillStatus = translateSettleBillStatus(res.settleBillList[i].status);
                            var orderNum = res.settleBillList[i].orderNum;
                            html += ('<li>'+
                            '<a href="javascript:void(0);" class="item-link list-button" style="line-height:normal;" onclick="getSettleBillDetail(\''+orderNum+'\')">'+
                            '<div class="item-inner">'+
                            '<table width="100%" style="color:#000000;border-collapse:separate; border-spacing:1px;">'+
                            '<tr><th style="text-align:left;">结算日期</th><th style="text-align:right;">结算金额</th><th rowspan="2" style="text-align:right;width:90px;color:'+(settleBillStatus === '付款成功'?'green':'red')+'">'+settleBillStatus+'</th></tr>'+
                            '<tr><td style="text-align:left;">'+new Date(res.settleBillList[i].settleDate.time).Format("yyyy-MM-dd")+'</td><td style="text-align:right;">'+res.settleBillList[i].settleAmount+'</td></tr>'+
                            '</table>'+
                            '</div>'+
                            '</a>'+
                            '</li>');
                        }
                        $$('.mf-settle-bill-list ul').append(html);
                        myApp.hidePreloader();
                        $$("#pageSettleBillListTitle").html(mfCusName);
                        document.title='结算查询';
                        mainView.router.load({pageName:'pageSettleBillList'});
                    }
                }else{
                    myApp.hidePreloader();
                    myApp.alert( res.msg,function(){
                        if(res.code === '-2'){
                            location.replace(location.href);
                        }
                    });
                }
            },
            error:function(){
                myApp.hidePreloader();
                myApp.alert( '查询出错啦');
            }
        });
    });
}

function translateRimitStatus(rs){
    if(rs==='INIT'){
        return '初始';
    }else if(rs === 'WAIT'){
        return '待付款';
    }else if(rs === 'REMIT_ING'){
        return '付款中';
    }else if(rs === 'FAIL'){
        return '付款失败';
    }else if(rs === 'SUCCESS'){
        return '付款成功';
    }else{
        return ts;
    }
}
function getSettleBillDetail(settleBillId){
    for(var i=0;i<settleBillList.length;i++){
        if(settleBillList[i].id==settleBillId){
            $$.ajax({
                type:'POST',
                url:  'customerRegisterSettleBillDetail.action',
                data:{
                    settleBillId:settleBillId
                },
                success: function(data){
                    if(res.code == '9990' || res.code == '9991'){
                        myApp.hidePreloader();
                        myApp.alert(res.msg);
                        $$("#password").val('');
                        mainView.router.load({pageName:'pageLogin'});
                    }
                    var res = eval('('+data+')');
                    if(res.code == '0'){
                        myApp.hidePreloader();
                        document.title = '结算详情';
                        mainView.router.load({
                            template: Template7.templates.pageSettleBillDetailInfoTemplate, // template already compiled and available as a property of Template7.templates
                            context: {
                                settleDate:new Date(settleBillList[i].settleDate.time).Format("yyyy-MM-dd"),
                                clearDateStart:new Date(settleBillList[i].clearDateStart.time).Format("yyyy-MM-dd"),
                                clearDateEnd:new Date(settleBillList[i].clearDateEnd.time).Format("yyyy-MM-dd"),
                                settleAmount:settleBillList[i].settleAmount,
                                bankAccountName:res.remitBill.bankAccountName,
                                status:translateRimitStatus(res.remitBill.status),
                                remitTime:new Date(res.remitBill.remitTime.time).Format("yyyy-MM-dd hh:mm")
                            }
                        });
                    }else{
                        myApp.hidePreloader();
                        myApp.alert( res.msg,function(){
                            if(res.code === '-2'){
                                location.replace(location.href);
                            }
                        });
                    }
                },
                error:function(){
                    myApp.hidePreloader();
                    myApp.alert( '查询出错啦');
                }
            });
            break;
        }
    }
}
function checkForgetPswd1Fields(){
    var phoneNumber = $$("#fp_phoneNo").val();
    var imgValiCode = $$("#imgValiCode").val();
    if(phoneNumber.length==11 && phoneNumber.match(/^1[3|4|5|7|8][0-9]\d{4,8}$/)!=null){
        var btnHtml = $$("#getValiCodeBtn").html().trim();
        if(btnHtml === '获取验证码'){
            $$("#getValiCodeBtn").removeClass("disabled");
        }
        var valiCode = $$("#valiCode").val();
        if(valiCode.length==6 && valiCode.match(/^\d{6}$/)!=null){
            $$("#forgetPswdBtn").removeClass("disabled");
        }else{
            $$("#forgetPswdBtn").addClass("disabled");
        }
    }else{
        $$("#getValiCodeBtn").addClass("disabled");
        $$("#forgetPswdBtn").addClass("disabled");
    }
}
$$('.myForgetFields').on('keyup parste change', checkForgetPswd1Fields);
var getValiCodeTimeItv;
$$("#getValiCodeBtn").click(function(){
    $$.ajax({
        type:'GET',
        url:  "../user/userAction_mobileCodeSimple.action",
        data:{
            phoneNo:$$("#fp_phoneNo").val(),
            terminalTypeId:$$("#terminalTypeId").val(),
            phoneNoOptType:'resetPswd'
        },
        success: function(data){
            var res = eval('('+data+')');
            if(res.code === '0'){
                $$("#getValiCodeBtn").addClass("disabled");
                $$("#getValiCodeBtn").html('60秒后重新获取');
                var time=60;
                getValiCodeTimeItv = setInterval(function(){
                    time--;
                    try{
                        if(time<1){
                            $$("#getValiCodeBtn").removeClass("disabled");
                            $$("#getValiCodeBtn").html('获取验证码');
                            clearInterval(getValiCodeTimeItv);
                        }else{
                            $$("#getValiCodeBtn").html(time+'秒后重新获取');
                        }
                    }catch(e){
                        console.dir(e);
                        clearInterval(getValiCodeTimeItv);
                    }
                },1000);
            }else{
                myApp.alert(res.msg);
            }
        }
    });
});
$$("#forgetPswdBtn").click(function(){
    $$("#forgetPswdBtn").addClass("disabled");
    $$.ajax({
        type:'GET',
        url:   '../user/verifiAction_customerRegisterValidatePhoneNo.action',
        data:{
        	terminalTypeId:$("#terminalTypeId").val(),
            mobile:$$("#fp_phoneNo").val(),
            valiCode:$$("#valiCode").val(),
            phoneNoOptType:'resetPswd'
        },
        success: function(data){
            var res = eval('('+data+')');
            if(res.code == '9990' || res.code == '9991'){
                myApp.hidePreloader();
                myApp.alert(res.msg);
                $$("#password").val('');
                mainView.router.load({pageName:'pageLogin'});
            }
            if(res.code === '0'){
                mainView.router.load({pageName: 'pageResetPswd'});
                document.title = '设置登陆密码';
                clearInterval(getValiCodeTimeItv);
            }else{
                $$("#forgetPswdBtn").removeClass("disabled");
                myApp.alert( res.msg);
            }
        },
        error: function(){
            $$("#forgetPswdBtn").removeClass("disabled");
            myApp.alert('获取验证码失败');
        }
    });
});
$$(".myPswd").on('keyup parste change',checkResetPswdNextStepBtn);
function checkResetPswdNextStepBtn(){
    var pswd = $$("#fp_password").val();
    var pswdConfirm = $$("#passwordConfirm").val();
    console.dir('['+pswd+']['+pswdConfirm+']['+pswd.match(/^[a-zA-Z0-9]{6,12}$/)+']');
    if(pswd.match(/^[a-zA-Z0-9]{6,12}$/)!=null && pswdConfirm === pswd){
        $$("#resetPswdBtn").removeClass("disabled");
    }else{
        $$("#resetPswdBtn").addClass("disabled");
    }
}
$$("#resetPswdBtn").click(function(){
    $$("#resetPswdBtn").addClass("disabled");
    $$.ajax({
        type:'GET',
        url:  '../user/userAction_customerResetPswd.action',
        data:{
            phoneNo:$$("#fp_phoneNo").val(),
            terminalTypeId:$$("#terminalTypeId").val(),
            password:$$("#fp_password").val()
        },
        success: function(data){
            var res = eval('('+data+')');
            if(res.code == '9990' || res.code == '9991'){
                myApp.hidePreloader();
                myApp.alert(res.msg);
                $$("#password").val('');
                mainView.router.load({pageName:'pageLogin'});
            }
            if(res.code == '0'){
                myApp.alert('修改成功',function(){location.replace(location.href);});
            }else{
                $$("#resetPswdBtn").removeClass("disabled");
                myApp.alert( res.msg);
            }
        },
        error:function(data){
            $$("#resetPswdBtn").removeClass("disabled");
            myApp.alert('修改失败');
        }
    });
});
function showMyQrCode(){
    var basePath = $$("#basePath").val();
    var terminalTypeId = $("#terminalTypeId").val();
    if(mfCusId){
        var url = basePath + 'user/userAction_customerRegisterFetchInfo.action?terminalTypeId='+terminalTypeId+'&activationCode='+mfCusId;
        console.dir(url);
        $("#myQRCode").html('');
        $("#myQRCodeImg").html('');
        $("#myQRCode").qrcode(url);
        mainView.router.load({pageName: 'pageQRCode'});
        
        $("#myQRCode").hide();
       //获取网页中的canvas对象  
        var mycanvas1=document.getElementsByTagName('canvas')[0]; 
      
       //将转换后的img标签插入到html中  
        var img=convertCanvasToImage(mycanvas1); 
        $('#myQRCodeImg').append("<p>长按识别二维码</p>");
        $('#myQRCodeImg').append(img);//imagQrDiv表示你要插入的容器id
    }
}

function convertCanvasToImage(canvas) {  
    //新Image对象，可以理解为DOM  
    var image = new Image();  
    // canvas.toDataURL 返回的是一串Base64编码的URL，当然,浏览器自己肯定支持  
    // 指定格式 PNG  
    image.src = canvas.toDataURL("image/png");  
    return image;  
}

function cashMoneyCheck(){
    var orderNum = $$("#orderNum").val();
    $$.ajax({
        type:'POST',
        url:  '../account/oACashMoneySafe_checkCashMoney.action',
        data:{
            orderNum:orderNum
        },
        success: function(data){
            var res = eval('('+data+')');
            if(res.code == '9990' || res.code == '9991'){
                myApp.hidePreloader();
                myApp.alert(res.msg);
                $$("#password").val('');
                mainView.router.load({pageName:'pageLogin'});
            }
            if(res.reqCode == '0000'){
                if(!confirm(res.reqMsg)){
                    return false;
                }
                cashMoney(orderNum,res.cashMoneyFee,res.userId,res.cashMoney);
            }else{
                myApp.hidePreloader();
                myApp.alert(res.msg,function(){
                    if(res.code === '-2'){
                        location.replace(location.href);
                    }
                });
            }
        },
        error:function(){
            myApp.hidePreloader();
            myApp.alert( '服务器异常,请稍后再试!');
        }
    });
}

function cashMoney(orderNum,cashMoneyFee,userId,cashMoney){
    $$.ajax({
        type:'POST',
        url:  '../account/oACashMoneySafe_cashMoney.action',
        data:{
            orderNum:orderNum,cashMoneyFee:cashMoneyFee,userId:userId,cashMoney:cashMoney
        },
        success: function(data){
            var res = eval('('+data+')');
            if(res.code == '9990' || res.code == '9991'){
                myApp.hidePreloader();
                myApp.alert(res.msg);
                $$("#password").val('');
                mainView.router.load({pageName:'pageLogin'});
            }
            if(res.code == '0000'){
                myApp.alert(res.msg);
            }else{
                myApp.hidePreloader();
                myApp.alert(res.msg,function(){
                    if(res.code === '-2'){
                        location.replace(location.href);
                    }
                });
            }
        },
        error:function(){
            myApp.hidePreloader();
            myApp.alert( '服务器异常,请稍后再试!');
        }
    });
}

$(function(){ 
	var storage = window.localStorage;    
    var phoneNo = storage["phoneNo"];    
    var password = storage["password"];
	if(phoneNo!="undefined" && password!="undefined"){
	    $("#phoneNo").val(phoneNo);  
        $("#password").val(password);    
	}
    
    if(checkLoginFields()){
         $("#loginBtn").removeClass("disabled");
         var btn = document.getElementById("loginBtn"); 
         //btn.click();
     }else{
        $("#loginBtn").addClass("disabled");
     }
});

function saveStorage(){  
    var phoneNo = $("#phoneNo").val();
    localStorage.setItem("phoneNo",phoneNo);
    var password =  $("#password").val();
    localStorage.setItem("password",password);
}



